package com.app.conrtoller;

import com.alibaba.fastjson.JSON;
import com.app.domain.ExternalResponse;
import com.app.domain.UploadParameter;
import com.app.domain.YjData;
import com.app.domain.gd.ResultJson;
import com.app.domain.gd.YfResponseResult;
import com.app.domain.gd.YfYjInfo;
import com.app.domain.gd.YfYjRealData;
import com.app.domain.hsy.SendMessage;
import com.app.service.SendMessageService;
import com.app.service.UploadParameterService;
import com.app.service.UploadService;
import com.app.service.YjDataService;
import com.app.utils.HttpClients;
import com.app.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 盐阜快速路
 */
@Slf4j
@RestController
@RequestMapping("/yfksl")
public class YfUploadController {
    @Value("${yj.yfksl.rwHost}")
    private String rwHost;
    @Value("${yj.yfksl.serviceHost}")
    private String serviceHost;
    @Value("${yj.yfksl.serviceHostss}")
    private String serviceHostss;
    @Value("${yj.yfksl.sbbh}")
    private String sbbh;
    @Autowired
    YjDataService yjDataService;
    @Autowired
    UploadParameterService uploadParameterService;
    @Autowired
    UploadService uploadService;
    @Autowired
    SendMessageService sendMessageService;

    @RequestMapping("/upload")
    @ResponseBody
    public ExternalResponse upload(@RequestParam(value = "ids[]") String[] ids) throws InterruptedException {
        ExternalResponse externalResponse = null;
/*        //首先校验token是否过期,如果过期则将新的token写入配置文件
        RefreshTokenResult refreshTokenResult = uploadService.sendJwjbTokenMessage(refreshTokenHost);
        if (refreshTokenResult == null || refreshTokenResult.getCode() != 1) {
            externalResponse = new ExternalResponse(0, "token过期", "");
            return externalResponse;
        }
        String access_token = refreshTokenResult.getData().getToken();*/
        int total = ids.length;
        int succTotal = 0;
        int failTotal = 0;
        StringBuffer responseContent = new StringBuffer();
        responseContent.append("本次共上传数据：【" + total + "】条,");

        for (String id : ids) {

            YjData yjData = yjDataService.findOne(id);
            UploadParameter uploadParameter = uploadParameterService.findOne("9");
            SendMessage sendMessage1 = sendMessageService.ConditionQuery2(id);
        /*    String busiType = sendMessage.getBusi_type();
            String uuid = sendMessage.getUuid();*/

            if (sendMessage1 == null) {
                String result = null;
                try {
                    result = HttpClients.doPost(rwHost,new HashMap<>());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ResultJson resultJson = (ResultJson) JSON.parseObject(StringUtil.replaceBlank(result), ResultJson.class);
                String uuid = null;
                if (resultJson.getCode() == 200) {
                    uuid = resultJson.getResult().get(0).getUuid();
                } else {
                    failTotal++;
                }
                YfYjInfo gdYjInfo = uploadService.getGdYjInfo(yjData, uploadParameter, uuid,"", sbbh);
                String s = JSON.toJSONString(gdYjInfo);
                YfResponseResult gdResponseResult = uploadService.sendGdMessage(serviceHost, s);
                if (gdResponseResult.getCode() == 200) {
                    //主表上传成功
                    SendMessage sendMessage = new SendMessage();
                    sendMessage.setSbbh(yjData.getDevice_code());
                    sendMessage.setLh(yjData.getBridge_code());
                    sendMessage.setKh(yjData.getDuct_code());
                    sendMessage.setBusi_type(gdYjInfo.getUuid());
                    sendMessage.setUpload_time(new Date());
                    sendMessage.setUuid(gdYjInfo.getSyjid());
                    sendMessage.setStatus("0");
                    sendMessageService.insert(sendMessage);
                    List<YfYjRealData> realDataList = uploadService.getYfYjRealData(yjData, gdYjInfo.getYajiangs().get(0).getHoleid(), sbbh);
                    for (YfYjRealData gdYjRealData : realDataList) {
                        uploadService.sendGdMessage(serviceHostss, JSON.toJSONString(gdYjRealData));
                    }
                    updateState("1", String.valueOf(yjData.getId()));
                    succTotal++;
                } else {
                    log.info("-------------压浆记录mudjack数据发送失败------------------------");
                    updateState("0", String.valueOf(yjData.getId()));
                    failTotal++;
                }
            } else {
                YfYjInfo gdYjInfo = uploadService.getGdYjInfo(yjData, uploadParameter, sendMessage1.getBusi_type(),sendMessage1.getUuid(), sbbh);
                YfResponseResult gdResponseResult = uploadService.sendGdMessage(serviceHost, JSON.toJSONString(gdYjInfo));
                if (gdResponseResult.getCode() == 200) {
                    List<YfYjRealData> realDataList = uploadService.getYfYjRealData(yjData, gdYjInfo.getYajiangs().get(0).getHoleid(), sbbh);
                    for (YfYjRealData gdYjRealData : realDataList) {
                        uploadService.sendGdMessage(serviceHostss, JSON.toJSONString(gdYjRealData));
                    }
                    updateState("1", String.valueOf(yjData.getId()));
                    succTotal++;
                } else {
                    updateState("0", String.valueOf(yjData.getId()));
                    failTotal++;
                }
            }
        }
        responseContent.append("成功【" + succTotal + "】条,失败" + failTotal + "条");
        externalResponse = new ExternalResponse(0, responseContent.toString(), "");
        return externalResponse;
    }

    private void updateState(String state, String id) {
        yjDataService.updateById(state, id);
    }
}
